<?php
include('common.php');

// returns TRUE if Var1, ... Var6 and Returns_To are all NULL for this definition.  this case can screw up the way 
// edit_instance is displayed.
function all_empty($def)
{
	global $vars;
	$everything = $vars;
	$everything[] = 'Returns_To';
	foreach ($everything as $e)
	{
		if (!is_null($def[$e]))
		{
			return FALSE;
		}
	} 
	return TRUE;
}

// BEGIN EXECUTION

// catch form submission if it was done
// save constant and redirect
if (!empty($_POST))
{
	$domain = mysql_real_escape_string($_POST['domain']);
	$line = mysql_real_escape_string($_POST['line']);
	$everything = $vars;
	$everything[] = 'Returns_To';
	foreach ($everything as $name)
	{
		if (!empty($_POST[$name]))
		{
			$value = mysql_real_escape_string($_POST[$name]);
			$name_text = $name . '_Text';
			if ($name == 'Returns_To')
			{
				sql_exec("UPDATE Instances SET $name=NULL WHERE Domain='$domain' AND Line_Number='$line' AND User='$user' ");
			} else {
				sql_exec("UPDATE Instances SET $name=NULL, $name_text=NULL WHERE Domain='$domain' AND Line_Number='$line' AND User='$user' ");
			}
			
			if (is_numeric($value))
			{
				sql_exec("UPDATE Instances SET $name='$value' WHERE Domain='$domain' AND Line_Number='$line' AND User='$user' ");
			} else {
				sql_exec("UPDATE Instances SET $name_text='$value' WHERE Domain='$domain' AND Line_Number='$line' AND User='$user' ");
			}
		}
	}
	update($user, $domain, $line);
	header("Location: edit_page.php?domain=$domain");
}


html_header("edit this step");

?>
<body>

<div id="container">

<?php header_div(); ?>

<div id="body">
<?php 

$instance = sql_row1("SELECT * FROM Instances WHERE Domain='$domain' AND Line_Number='$line' AND User='$user'");
$call = $instance['Fxn_Call'];
$def = sql_row1("SELECT * FROM Definitions WHERE Fxn_Call='$call' AND (User='$user' OR User IS NULL)");


// for read-only variables, we want to include SELECT Var1 FROM Instances WHERE Fxn_Call='form_input' and join that to 
// the result from querying Variables

$args = $vars;
array_push($args, 'Returns_To');

// add a blank space if this function does not have any arguments or a return value

// display the <form> for all the arguments here
// if they are all NULL, don't do it.
if (!all_empty($def))
{
	echo "<form action=\"edit_instance.php\" method=\"post\">\n";
	foreach ($args as $v)
	{
		// if the variable is defined, display the right menu for it
		if (!is_null($def[$v]))
		{
			if ($v == 'Var2')
			{
				if ($call == 'arithmetic')
				{
					$sql = "SELECT ID FROM Variables WHERE ID <= -7 AND ID >= -10";
				} elseif ($call == 'if' || $call == 'while') {
					$sql = "SELECT ID FROM Variables WHERE ID <= -1 AND ID >= -6";
				} else {
					$sql = "SELECT ID FROM Variables WHERE (ID > -1 AND Domain='$domain' AND User='$user') AND Name IS NOT NULL ORDER BY ID DESC";
					// we can have a form field here, if there is a form
				}
			} else {
				if ($v == 'Returns_To')
				{
					$sql = "SELECT ID FROM Variables WHERE ID > -1 AND Domain='$domain' AND User='$user' AND Name IS NOT NULL";
				} elseif ($call == 'for' && $v == 'Var1') { 
					// just like the normal case except that we can't use a constant for var1
					// (being the counter in 'for')
					$sql = "SELECT ID FROM Variables WHERE (ID > -1 AND Domain='$domain' AND User='$user') AND Name IS NOT NULL ORDER BY ID DESC";
				} else  {
					$sql = "SELECT ID FROM Variables WHERE (ID > -1 AND Domain='$domain' AND User='$user') AND Name IS NOT NULL ORDER BY ID DESC";
					// can have a form field here too
					// since the two cases where form fields are OK have identical sql queries, use the query
					// to determine if form fields should be added (safe_sql below)
				}
			}
			$safe_sql = "SELECT ID FROM Variables WHERE (ID > -1 AND Domain='$domain' AND User='$user') AND Name IS NOT NULL ORDER BY ID DESC";

			$result = mysql_query($sql) or die("could not $sql: " . mysql_error());
			// that was nasty


			// label: argument name
			$border_label = $def[$v];
			if (optional($v, $call) == TRUE && $v != 'Returns_To')
			{
				$border_label .= ' (optional)';
			}
			// for now ignore other stuff if this is return
			if ($v == 'Returns_To')
			{
				$border_label = 'Returns To';
			}
			echo "<p>$border_label \n";



			// go through all the variables we can choose from for this argument 
			// in a <select>
			echo "<select name=\"$v\">\n";
			
			// find the default
			$default = $instance[$v];
			while ($row = mysql_fetch_array($result))
			{
				$id = $row['ID'];
				$name_row = sql_row1("SELECT Name FROM Variables WHERE ID='$id' ");
				// for the it\'s a variable problem
				$name = stripslashes($name_row['Name']);
				$selected = ($id == $default) ? ' selected ' : '';
				// add the <option>
				echo "<option $selected value=\"$id\">$name</option>\n";
			}
	
			// boxes for all the table values
			$v_text = $v . '_Text';
			$default = $instance[$v_text];
			if (!($call == 'arithmetic' && $v == 'Var2') && $v != 'Returns_To' && !($call == 'database' && $v='Var1'))
			{
				//die("looking for table values");
				$table_values = available_table_values($user, $domain, $line);
				foreach ($table_values as $value_in_db=>$value_to_user)
				{
					$selected = ($value_in_db == $default) ? ' selected ' : '';
					
					// the $value_in_db is where there is usually an integral variable ID
					echo "<option $selected value=\"$value_in_db\">$value_to_user</option>\n";
				}
			}
	
			// boxes for the form fields
			if ($sql == $safe_sql)
			{
				$form_fields_sql = add_form_fields();
				if (empty($form_fields_sql))
				{
					//die("no fields?");
				} else {
					$result = sql_exec($form_fields_sql);
					while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
					{
						$field_name = $row['Var1_Text'];
						$field_to_user = $field_name . ' (from a form)';
						$selected = ($field_name == $default) ? ' selected ' : '';
						
						echo "<option $selected value=\"$field_name\">$field_to_user</option>\n";
					}
				}
			}
			// close the <select>
			echo "</select>\n";
			echo "</p>\n";

			if (mysql_num_rows($result) == 0 && count($table_values) == 0 && empty($form_fields_sql))
			{
				echo "<p>you need to <a href=\"memory.php?domain=$domain\">add a variable</a></p>\n";
			}
		} // end if $v is not null in definition
	}
	echo "<input type=\"submit\" value=\"save\" />\n";
	echo "<input type=\"hidden\" name=\"domain\" value=\"$domain\" />\n";
	echo "<input type=\"hidden\" name=\"line\" value=\"$line\" />\n";
	echo "</form>\n";
} else { // end if all empty (no args or return value)
	echo "<p>looks like you're set.</p>\n";
}

echo "<p><a href=\"edit_page.php?domain=$domain\">go back to editing</a></p>\n";

// delete 
// don't allow deleting endform, endol, or endul
if ($call != 'endform' && $call != 'endul' && $call != 'endol')
{
	echo "<p><a href=\"delete_instance.php?line=$line&domain=$domain\">delete</a></p>";
}

echo footer();
?>

</div>



</div>
</body>
</html>
